import { defineStore } from 'pinia'

export const cart = defineStore('cart', {
  state() {
    return {
      data: [],
      cartData: [],
    }
  },
  actions: {
    async feachData() {
      try {
        let res = await fetch('api/data/index.json').then((body) => body.json())
        // console.log(res)
        this.data = res.data
        // console.log(data)
      } catch (e) {
        console.log(e)
      }
    },
    add(current) {
      current.inventory--
      let target = this.cartData.find((item) => item.id === current.id)
      if (!target) {
        let obj = {
          title: current.title,
          price: current.price,
          count: 1,
          id: current.id,
        }
        this.cartData.push(obj)
      } else {
        target.count++
      }

      //   current.inventory = current.inventory - 1
    },
    del(current, i) {
      current.count--
      if (current.count === 0) {
        this.cartData.splice(i, 1)
      }
      console.log(current.count)
      let target = this.data.find((item) => item.id === current.id)
      console.log(target)
      if (target) {
        // target.data.inventory++
        target.inventory++
      }
    },
  },
  getters: {
    total(state) {
      return state.cartData
        .reduce((total, item) => {
          return (total += item.price * item.count)
        }, 0)
        .toFixed(2)
    },
  },
})
